package com.xuecheng.ucenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.utils.Constant;
import com.xuecheng.ucenter.model.dto.UserRegisterDto;
import com.xuecheng.ucenter.model.dto.UserRepalcePassDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.model.po.XcUserRole;
import com.xuecheng.ucenter.service.UserRoleService;
import com.xuecheng.ucenter.service.UserService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.UUID;

@RestController
public class UserController {

    @Autowired
    private UserService userService ;

    @Autowired
    private UserRoleService userRoleService ;

    @Autowired
    PasswordEncoder passwordEncoder;

    String ConstantCodeFrefx = "xuecheng:code:";

    @Autowired
    private RedisTemplate<String,String> redisTemplate ;

//注册
    @PostMapping("/register")
    @Transactional
    public void register(@RequestBody UserRegisterDto userRegisterDto){
        if(StringUtils.isEmpty(userRegisterDto.getUsername())||StringUtils.isEmpty(userRegisterDto.getNickname())){
            throw new XueChengPlusException("账号和昵称不能为空");
        }
//        校验验证码
        UserRepalcePassDto userDto = checkCode(userRegisterDto);

        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(XcUser::getCellphone,userRegisterDto.getCellphone());
        queryWrapper.eq(XcUser::getUsername,userRegisterDto.getUsername());
        XcUser xcUser = userService.getOne(queryWrapper);
        if(!StringUtils.isEmpty(xcUser)){
            throw new XueChengPlusException("您好，该账号已存在，请重新输入");
        }

        xcUser = new XcUser();
        BeanUtils.copyProperties(userRegisterDto,xcUser);
        //        向数据库新增记录
        String userId = UUID.randomUUID().toString();

        xcUser.setId(userId);
        xcUser.setName(userRegisterDto.getUsername());
        String encode = passwordEncoder.encode(userDto.getPassword());
        xcUser.setPassword(encode);
        xcUser.setUpdateTime(LocalDateTime.now());
        xcUser.setUtype("101001");//学生类型
        xcUser.setStatus("1");//用户状态
        xcUser.setCreateTime(LocalDateTime.now());
        boolean b1 = userService.save(xcUser);
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setId(UUID.randomUUID().toString());
        xcUserRole.setUserId(userId);
        xcUserRole.setRoleId("17");//学生角色
        xcUserRole.setCreateTime(LocalDateTime.now());
        boolean b2 = userRoleService.save(xcUserRole);

        if(!(b1||b2)){
            throw new XueChengPlusException("系统忙，请重新注册");
        }
    }




    //修改密码
    @PostMapping("/findpassword")
    public void findpassword(@RequestBody UserRepalcePassDto userRepalcePassDto){
        UserRepalcePassDto userRepalcePassDto1 = checkCode(userRepalcePassDto);

        //修改密码
        String cellphone = userRepalcePassDto.getCellphone();
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>() ;
        queryWrapper.eq(XcUser::getCellphone,cellphone);
        XcUser user = userService.getOne(queryWrapper);
        if(StringUtils.isEmpty(user)){
            throw new XueChengPlusException("手机号输入错误请重新输入");
        }

        String encode = passwordEncoder.encode(userRepalcePassDto1.getPassword());
        user.setPassword(encode);
        user.setUpdateTime(LocalDateTime.now());
       // userService.updateById(user) ;
//        return "signE";
    }

    @NotNull
    private UserRepalcePassDto checkCode(@RequestBody UserRepalcePassDto userRepalcePassDto) {
        String checkcode = userRepalcePassDto.getCheckcode();
        String confirmpwd = userRepalcePassDto.getConfirmpwd();
        String password = userRepalcePassDto.getPassword();
        if(StringUtils.isEmpty(checkcode)){
            throw new XueChengPlusException("请输入验证码");
        }
        if(StringUtils.isEmpty(password)||StringUtils.isEmpty(confirmpwd)){
            throw new XueChengPlusException("请输入密码");
        }

        if(!confirmpwd.equals(password)){
            throw new XueChengPlusException("确认密码输入错误请重新输入");
        }

//        获取验证码
        String code = redisTemplate.opsForValue().get(ConstantCodeFrefx+userRepalcePassDto.getCellphone());
        if(StringUtils.isEmpty(code)){
            throw new XueChengPlusException("验证码失效，请重新发送验证码");
        }

        if(!code.equals(checkcode)){
            throw new XueChengPlusException("验证码输入错误请重新输入");
        }
        //删除使用过的key
        redisTemplate.delete(Constant.REDIS_CODE_FREFX+userRepalcePassDto.getCellphone());
        return userRepalcePassDto;
    }
}
